package com.example.seabedmusic.views;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.seabedmusic.R;
import com.example.seabedmusic.adapter.WoDeAdapter;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.utils.LocalMusicManager;
import com.example.seabedmusic.utils.LocalMusicScanner;
import com.example.seabedmusic.utils.PermissionManager;

import java.util.ArrayList;
import java.util.List;

public class LocalMusicActivity extends AppCompatActivity implements WoDeAdapter.OnSongClickListener {
    private static final int PERMISSION_REQUEST_CODE = 1001;

    private RecyclerView rvLocalMusic;
    private TextView tvMusicCount;
    private WoDeAdapter adapter;
    private List<Song> localSongs = new ArrayList<>();
    private LocalMusicManager localMusicManager;
    private boolean hasRequestedPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_music);

        localMusicManager = LocalMusicManager.getInstance(this);
        initViews();

        // 检查并请求权限
        checkAndRequestPermissions();
    }

    private void initViews() {
        rvLocalMusic = findViewById(R.id.rvLocalMusic);
        tvMusicCount = findViewById(R.id.tvMusicCount);

        // 设置返回按钮
        findViewById(R.id.ivBack).setOnClickListener(v -> finish());

        // 初始化RecyclerView
        adapter = new WoDeAdapter(localSongs);
        adapter.setOnSongClickListener(this);
        adapter.setShowMoreOptions(true);
        adapter.setIsLocalMusic(true); // 重要：设置为本地音乐页面

        rvLocalMusic.setLayoutManager(new LinearLayoutManager(this));
        rvLocalMusic.setAdapter(adapter);
    }

    /**
     * 检查并请求权限
     */
    private void checkAndRequestPermissions() {
        if (PermissionManager.hasRequiredPermissions(this)) {
            // 已有权限，加载音乐
            loadLocalMusic();
        } else {
            // 请求权限
            if (!hasRequestedPermission) {
                showPermissionExplanationDialog();
            } else {
                // 如果已经请求过但用户拒绝了，直接显示空状态
                showNoPermissionState();
            }
        }
    }

    /**
     * 显示权限说明对话框
     */
    private void showPermissionExplanationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("需要存储权限");
        builder.setMessage("为了扫描您设备上的本地音乐文件，需要访问存储权限。请允许权限以继续使用本地音乐功能。");
        builder.setPositiveButton("确定", (dialog, which) -> {
            PermissionManager.requestPermissions(this, PERMISSION_REQUEST_CODE);
            hasRequestedPermission = true;
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
            showNoPermissionState();
            finish();
        });
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 显示无权限状态
     */
    private void showNoPermissionState() {
        localSongs.clear();
        adapter.notifyDataSetChanged();
        tvMusicCount.setText("无访问权限");

        // 显示提示信息
        Toast.makeText(this, "无法访问本地音乐，请授予存储权限", Toast.LENGTH_LONG).show();

        // 可以在这里显示一个友好的UI提示用户去设置中授权
        showPermissionSettingsDialog();
    }

    /**
     * 显示前往设置授权的对话框
     */
    private void showPermissionSettingsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("权限被拒绝");
        builder.setMessage("存储权限被拒绝，无法扫描本地音乐。您可以在设置中手动授权。");
        builder.setPositiveButton("前往设置", (dialog, which) -> {
            // 跳转到应用设置页面
            openAppSettings();
        });
        builder.setNegativeButton("稍后再说", null);
        builder.show();
    }

    /**
     * 跳转到应用设置页面
     */
    private void openAppSettings() {
        try {
            android.content.Intent intent = new android.content.Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            android.net.Uri uri = android.net.Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "无法打开设置页面", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadLocalMusic() {
        // 显示加载状态
        tvMusicCount.setText("扫描中...");

        new Thread(() -> {
            try {
                // 扫描设备本地音乐
                List<Song> scannedSongs = LocalMusicScanner.scanLocalMusic(this);
                // 获取下载的音乐
                List<Song> downloadedSongs = localMusicManager.getLocalSongs();

                runOnUiThread(() -> {
                    localSongs.clear();
                    localSongs.addAll(scannedSongs);
                    localSongs.addAll(downloadedSongs);
                    adapter.notifyDataSetChanged();

                    updateMusicCount();

                    if (localSongs.isEmpty()) {
                        Toast.makeText(this, "未找到本地音乐文件", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, "找到 " + localSongs.size() + " 首本地音乐", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(this, "扫描本地音乐失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    updateMusicCount();
                });
            }
        }).start();
    }

    private void updateMusicCount() {
        String countText = "共 " + localSongs.size() + " 首歌曲";
        tvMusicCount.setText(countText);
    }

    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (PermissionManager.isPermissionGranted(grantResults)) {
                // 权限被授予，加载音乐
                Toast.makeText(this, "权限已授予，正在扫描音乐...", Toast.LENGTH_SHORT).show();
                loadLocalMusic();
            } else {
                // 权限被拒绝
                boolean shouldShowRationale = false;
                for (String permission : permissions) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                        shouldShowRationale = true;
                        break;
                    }
                }

                if (shouldShowRationale) {
                    // 用户拒绝但未选择"不再询问"，可以再次解释
                    showPermissionExplanationDialog();
                } else {
                    // 用户选择"不再询问"，显示前往设置的提示
                    showNoPermissionState();
                }
            }
        }
    }

    @Override
    public void onSongClick(Song song) {
        playSong(song);
    }

    @Override
    public void onMoreClick(Song song) {
        // 在本地音乐页面，更多操作已经在Adapter内部处理
        // 这里只需要记录日志，不需要显示弹窗
        Log.d("LocalMusicActivity", "更多操作点击: " + song.getTitle());
    }

    /**
     * 播放歌曲
     */
    private void playSong(Song song) {
        // 跳转到播放页面
        android.content.Intent intent = new android.content.Intent(this, MusicPlayerActivity.class);
        intent.putExtra("song_title", song.getTitle());
        intent.putExtra("song_artist", song.getArtist());
        intent.putExtra("song_url", song.getUrl());
        intent.putExtra("song_cover", song.getCover());
        intent.putExtra("song_album", song.getAlbum());
        intent.putExtra("song_lyrics", song.getLyrics());

        // 如果是本地音乐，设置文件路径
        if (song.isLocal() || song.getFilePath() != null) {
            intent.putExtra("song_url", song.getFilePath());
        }

        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 如果之前没有权限，现在检查是否已经授权
        if (!PermissionManager.hasRequiredPermissions(this)) {
            checkAndRequestPermissions();
        } else {
            // 刷新数据
            refreshLocalMusic();
        }

        // 确保Adapter设置正确
        if (adapter != null) {
            adapter.setIsLocalMusic(true);
            adapter.setShowMoreOptions(true);
            Log.d("LocalMusicActivity", "onResume: 设置Adapter为本地音乐模式");
        }
    }

    /**
     * 刷新本地音乐列表
     */
    private void refreshLocalMusic() {
        if (!PermissionManager.hasRequiredPermissions(this)) {
            return;
        }

        new Thread(() -> {
            try {
                // 扫描设备本地音乐
                List<Song> scannedSongs = LocalMusicScanner.scanLocalMusic(this);
                // 获取下载的音乐
                List<Song> downloadedSongs = localMusicManager.getLocalSongs();

                runOnUiThread(() -> {
                    localSongs.clear();
                    localSongs.addAll(scannedSongs);
                    localSongs.addAll(downloadedSongs);
                    adapter.notifyDataSetChanged();
                    updateMusicCount();
                });
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(this, "刷新失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
}